package com.zd.commodity.productMng.biz.impl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zd.commodity.biz.impl.BaseBiz;
import com.zd.commodity.productMng.biz.IProductAttrValueBiz;
import com.zd.commodity.productMng.dao.IProductAttrDao;
import com.zd.commodity.productMng.dao.IProductAttrValueDao;
import com.zd.commodity.productMng.dao.IProductDao;
import com.zd.commodity.productMng.entity.ProductAttrValue;

@Service("productAttrValueBiz")
public class ProductAttrValueBizImpl extends BaseBiz<ProductAttrValue> implements
		IProductAttrValueBiz {

	private IProductAttrValueDao productAttrValueDao;

	public IProductAttrValueDao getProductAttrValueDao() {
		return productAttrValueDao;
	}

	@Autowired
	public void setProductAttrValueDao(IProductAttrValueDao productAttrValueDao) {
		this.productAttrValueDao = productAttrValueDao;
	    this.setBaseDao(productAttrValueDao);
	}
	
	@Autowired
	private IProductAttrDao productAttrDao;
	@Autowired
	private IProductDao productDao;
	
	public String[] saveProductAttrValue(HttpServletRequest request){
		String pId = request.getParameter("pId"); //Id
		String[] valueIdList = request.getParameterValues("productAttrValueId");
		String[] attrIdList = request.getParameterValues("productAttrId");
		String[] valueList = request.getParameterValues("value");
		
		
		for(int i=0;i<attrIdList.length;i++){
			
			//判断属性值value是否为空
			boolean flag = valueList[i].trim() ==null || "".equals(valueList[i].trim());
			//判断属性值Id AttrValueId是否为空
			boolean b = valueIdList[i] ==null || "".equals(valueIdList[i]);
			
			if(!flag){
				//若value不为空，看AttrValueId是否为空   AttrValueId为空则添加；AttrValueId不为空则修改
				if(!b){//有AttrValueId则修改
					ProductAttrValue pav=productAttrValueDao.get(Long.valueOf(valueIdList[i]));
					pav.setValue(valueList[i]);
					productAttrValueDao.update(pav);
				}else{//无AttrValueId则添加
					ProductAttrValue pav=new ProductAttrValue();
					pav.setProduct(productDao.get(Long.valueOf(pId)));
					pav.setProductAttr(productAttrDao.get(Long.valueOf(attrIdList[i])));
					pav.setValue(valueList[i]);
					productAttrValueDao.add(pav);
					
					valueIdList[i]=pav.getId().toString();
				}
				
			}else{
				//若value为空，看AttrValueId是否为空   AttrValueId为空无操作；AttrValueId不为空则删除
				if(!b){
					productAttrValueDao.delete(Long.valueOf(valueIdList[i]));
					valueIdList[i]="";
				}
			}
		}
		
		return valueIdList;
	}
	
	
	
	public ProductAttrValue findByProductId(Long productId){
		return productAttrValueDao.findByProductId(productId);
	}

}
